package com.ldkj.panzh.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hikvision.artemis.sdk.ArtemisHttpUtil;
import com.hikvision.artemis.sdk.config.ArtemisConfig;
import com.ldkj.panzh.param.VehicleRecordParam;
import com.ldkj.panzh.service.VehicleRecordService;
import com.ldkj.panzh.utils.CommentUtils;
import com.ldkj.panzh.vo.VehicleRecordVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 车辆记录查询 实现类
 *
 * @author qiancheng
 * @date 2025-11-19
 */
@Slf4j
@Service
public class VehicleRecordServiceImpl implements VehicleRecordService {

    // API网关相关常量
    private static final String ARTEMIS_PATH = "/artemis";
    // 车辆过车记录查询接口（事件服务）
    private static final String GET_VEHICLE_RECORD_API = ARTEMIS_PATH + "/api/eventService/v1/eventSubscriptionByEventTypes";

    // 接口参数常量
    private static final String PAGE_NO = "pageNo";
    private static final String PAGE_SIZE = "pageSize";
    private static final String SUCCESS_CODE = "0";

    @Autowired
    public CommentUtils commentUtils;

    /**
     * 查询车辆过车记录
     *
     * @param vehicleRecordParam 查询参数
     * @return 车辆记录列表
     */
    @Override
    public List<VehicleRecordVO> queryVehicleRecords(VehicleRecordParam vehicleRecordParam) throws Exception {

        //设置平台参数（优先使用参数中的值，否则使用配置文件默认值）
        ArtemisConfig config = commentUtils.createArtemisConfig(
                vehicleRecordParam.getAppKey(),
                vehicleRecordParam.getAppSecret(),
                vehicleRecordParam.getHost());

        // 准备基础参数
        Map<String, Object> paramMap = new HashMap<>(16);
        paramMap.put(PAGE_NO, vehicleRecordParam.getPageNo());
        paramMap.put(PAGE_SIZE, vehicleRecordParam.getPageSize());

        // 时间范围（如果未传入，默认查询今天）
        String startTime = vehicleRecordParam.getStartTime();
        String endTime = vehicleRecordParam.getEndTime();
        
        if (startTime == null || startTime.isEmpty()) {
            // 默认今天00:00:00
            startTime = java.time.LocalDate.now().atStartOfDay()
                    .format(java.time.format.DateTimeFormatter.ISO_LOCAL_DATE_TIME) + ".000+08:00";
        }
        if (endTime == null || endTime.isEmpty()) {
            // 默认今天23:59:59
            endTime = java.time.LocalDate.now().atTime(23, 59, 59)
                    .format(java.time.format.DateTimeFormatter.ISO_LOCAL_DATE_TIME) + ".999+08:00";
        }
        
        paramMap.put("startTime", startTime);
        paramMap.put("endTime", endTime);
        
        // 事件类型：车辆过车事件
        paramMap.put("eventTypes", Arrays.asList(197121));
        
        // 事件目的地（必填参数）：0-设备，1-区域
        // 使用数组格式，查询所有设备和区域的事件
        paramMap.put("eventDest", Arrays.asList(0, 1));

        // 添加可选参数
        if (vehicleRecordParam.getPlateNo() != null && !vehicleRecordParam.getPlateNo().isEmpty()) {
            paramMap.put("plateNo", vehicleRecordParam.getPlateNo());
        }
        if (vehicleRecordParam.getPlateColor() != null) {
            paramMap.put("plateColor", vehicleRecordParam.getPlateColor());
        }
        if (vehicleRecordParam.getVehicleType() != null) {
            paramMap.put("vehicleType", vehicleRecordParam.getVehicleType());
        }
        if (vehicleRecordParam.getCameraIndexCodes() != null && !vehicleRecordParam.getCameraIndexCodes().isEmpty()) {
            paramMap.put("cameraIndexCodes", vehicleRecordParam.getCameraIndexCodes());
        }
        if (vehicleRecordParam.getRegionIndexCodes() != null && !vehicleRecordParam.getRegionIndexCodes().isEmpty()) {
            paramMap.put("regionIndexCodes", vehicleRecordParam.getRegionIndexCodes());
        }
        if (vehicleRecordParam.getIsSubRegion() != null) {
            paramMap.put("isSubRegion", vehicleRecordParam.getIsSubRegion());
        }
        if (vehicleRecordParam.getOrderBy() != null && !vehicleRecordParam.getOrderBy().isEmpty()) {
            paramMap.put("orderBy", vehicleRecordParam.getOrderBy());
        }
        if (vehicleRecordParam.getOrderType() != null && !vehicleRecordParam.getOrderType().isEmpty()) {
            paramMap.put("orderType", vehicleRecordParam.getOrderType());
        }

        Map<String, String> pathMap = Collections.singletonMap("https://", GET_VEHICLE_RECORD_API);
        List<VehicleRecordVO> resultList = new ArrayList<>();

        try {
            String body = JSON.toJSONString(paramMap);
            log.info("查询车辆记录请求参数: {}", body);

            String response = ArtemisHttpUtil.doPostStringArtemis(
                    config, pathMap, body, null, null, "application/json");
            log.info("查询车辆记录响应: {}", response);

            JSONObject jsonObject = JSON.parseObject(response);
            String code = jsonObject.getString("code");

            if (SUCCESS_CODE.equals(code)) {
                JSONObject data = jsonObject.getJSONObject("data");
                if (data != null) {
                    String list = data.getString("list");
                    if (list != null && !list.isEmpty()) {
                        resultList = JSON.parseArray(list, VehicleRecordVO.class);
                    }
                }
            } else {
                String errorMsg = String.format("接口返回错误: %s，响应内容: %s",
                        jsonObject.getString("msg"), response);
                log.error(errorMsg);
                throw new Exception(errorMsg);
            }
        } catch (Exception e) {
            String errorMsg = "查询车辆记录失败";
            log.error(errorMsg, e);
            throw new Exception(errorMsg, e);
        }
        return resultList;
    }

    /**
     * 查询车辆统计信息
     *
     * @param vehicleRecordParam 查询参数
     * @return 统计数据（总数、车辆类型分布、进出统计等）
     */
    @Override
    public Map<String, Object> queryVehicleStats(VehicleRecordParam vehicleRecordParam) throws Exception {
        // 查询所有车辆记录
        List<VehicleRecordVO> allRecords = queryVehicleRecords(vehicleRecordParam);

        // 统计数据
        Map<String, Object> stats = new HashMap<>(16);
        int totalCount = allRecords.size();
        int inCount = 0;
        int outCount = 0;
        Map<String, Integer> plateColorStats = new HashMap<>();
        Map<String, Integer> vehicleTypeStats = new HashMap<>();

        for (VehicleRecordVO record : allRecords) {
            // 统计进出方向
            if (record.getDirection() != null) {
                if (record.getDirection() == 0) {
                    inCount++;
                } else if (record.getDirection() == 1) {
                    outCount++;
                }
            }

            // 统计车牌颜色
            if (record.getPlateColorName() != null) {
                plateColorStats.merge(record.getPlateColorName(), 1, Integer::sum);
            }

            // 统计车辆类型
            if (record.getVehicleTypeName() != null) {
                vehicleTypeStats.merge(record.getVehicleTypeName(), 1, Integer::sum);
            }
        }

        stats.put("totalCount", totalCount);
        stats.put("inCount", inCount);
        stats.put("outCount", outCount);
        stats.put("plateColorStats", plateColorStats);
        stats.put("vehicleTypeStats", vehicleTypeStats);

        return stats;
    }
}
